package cn.tedu.ems.interceptors;

import cn.tedu.ems.pojo.vo.UserVO;
import cn.tedu.utils.JwtUtil;
import cn.tedu.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从redis中取出token
        //不成功则抛异常,然后异常中返回错误信息,返回一个重定向提示
        String token = request.getHeader("token");//取出对应的token
        log.debug("从请求头中取出来的token:{}", token);
        //在redis中查找对应的token,
//        Object o = redisUtil.get("login:" + userId);
//        log.debug("从redis中取出来的一条jwt数据:{}", o);
        Claims claims = JwtUtil.parseJWT(token);
        //解析出userVO
        UserVO userVO = UserVO.formJson(claims.getSubject());
        if (userVO == null) {
            log.debug("从redis中取出来的userVO为空");
            throw new RuntimeException("token无效");
        }

        return HandlerInterceptor.super.preHandle(request
                , response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
